import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { getDynamicFonts } from '@/utils/fontUtils';
import ReleasePopUp from '@/pages/Settings/Components/ReleasePopUp';
import { motion, AnimatePresence } from 'framer-motion';
import { request } from '@/api/request';


interface PlanInfoProps {
    planType?: string;
    membershipTier?: number | null;
}

const PlanInfo: React.FC<PlanInfoProps> = ({ planType = 'Free', membershipTier }) => {
    const { t, i18n } = useTranslation();
    const dynamicFonts = getDynamicFonts(i18n);
    const [isModalOpen, setIsModalOpen] = useState(false);

    // membershipTier 未加载时不渲染内容，防止按钮闪烁
    if (membershipTier === undefined) {
        return null;
        // 或者 return <div>加载中...</div>;
    }

    const handleCancelSubscription = async () => {
        try {
            const res = await request.post('/api/stripe/cancel-subscription');
            // console.log(res);
            if (res.status === 200) {
                console.log('取消订阅成功，立即更新前端数据');

                // 立即更新localStorage中的用户数据
                const userDataStr = localStorage.getItem('userData');
                if (userDataStr) {
                    try {
                        const userData = JSON.parse(userDataStr);
                        const updatedUserData = {
                            ...userData,
                            vip_live: null, // 取消订阅后设置为null
                            // tokens_balance保持不变，取消订阅不影响余额
                        };

                        console.log('取消订阅前的用户数据:', userData);
                        console.log('取消订阅后的用户数据:', updatedUserData);

                        // 更新localStorage
                        localStorage.setItem('userData', JSON.stringify(updatedUserData));

                        // 立即触发UI更新事件
                        console.log('触发userLoginStatusChanged事件...');
                        window.dispatchEvent(new CustomEvent('userLoginStatusChanged'));

                        // 再次触发事件确保所有组件都收到
                        setTimeout(() => {
                            console.log('再次触发userLoginStatusChanged事件确保所有组件更新');
                            window.dispatchEvent(new CustomEvent('userLoginStatusChanged'));
                        }, 100);

                        // 尝试刷新Token余额UI（保持原有余额，只是刷新显示）
                        try {
                            // 动态导入TokenBalance组件的刷新函数
                            const { refreshTokenBalance } = await import('@/components/TokenBalance');
                            refreshTokenBalance(updatedUserData.tokens_balance);
                            console.log('Token余额UI已刷新');
                        } catch (e) {
                            console.error('刷新Token余额UI失败:', e);
                        }

                        console.log('localStorage和UI事件已更新，用户应该立即看到VIP状态变化');

                    } catch (parseError) {
                        console.error('解析用户数据失败:', parseError);
                    }
                }

                alert("Cancel successfully!")

                // 等待500ms让用户看到VIP状态变化，然后刷新页面
                setTimeout(() => {
                    console.log('取消订阅UI更新完成，刷新页面确保数据一致性');
                    window.location.reload();
                }, 500);
            }
            // You might want to handle successful cancellation here
            // For example, show a success message or refresh user data
        } catch (error) {
            console.error('Failed to cancel subscription:', error);
            // Handle error (e.g., show an error message)
        }
    };

    return (
        <div className="w-full relative bg-zinc-900 rounded-[10px] border border-[#282828] mx-auto bg-gradient-to-r from-[#4D1D28] to-[#1F1F1F] mb-5 md:mb-10">
            <div style={{ fontFamily: dynamicFonts.font3 }} className="md:flex px-8 py-6 flex-col md:flex-row items-center">
                {/* 当前的会员等级  */}
                <div className="flex gap-x-2 mb-4 md:mb-0">
                    <div style={{ fontFamily: dynamicFonts.font1 }} className="text-white text-base font-medium leading-relaxed">
                        {t('settings.currentPlan')}
                    </div>
                    <div className="text-[#E75275] text-base font-medium leading-relaxed">
                        {planType}
                    </div>
                </div>

                {/* 升级到高级会员 - 只有当membershipTier为null时显示 */}
                {membershipTier === null && (
                    <motion.div className="ml-auto">
                        <motion.a
                            className="relative flex justify-center w-full items-center rounded-[10px] primary-gradient hover:text-white text-sm font-medium p-2.5 h-10 text-white focus:text-white active:text-white no-underline cursor-pointer"
                            href="/subscriptions"
                            style={{ background: 'rgb(236,90,121)' }}
                            whileHover={{
                                scale: 1.1,
                                y: -4,
                                boxShadow: "0 8px 16px rgba(236,90,121, 0.4)"
                            }}
                            whileTap={{ scale: 0.95 }}
                            initial={{ opacity: 0, x: 20 }}
                            animate={{ opacity: 1, x: 0 }}
                            transition={{
                                type: "spring",
                                stiffness: 400,
                                damping: 10
                            }}
                        >
                            <div className="flex justify-center items-center">
                                <div>
                                    {t('settings.upgradeToPremium')}
                                </div>
                            </div>
                        </motion.a>
                    </motion.div>
                )}

                {/* 解除绑定按钮 和升级会员的按钮 - 只有当membershipTier不为null时显示 */}
                {membershipTier !== null && (
                    <div className="ml-auto flex">
                        {/* 升级会员的按钮  */}
                        <div className="mr-3 ">
                            <motion.a
                                className="relative flex justify-center w-full hover:text-white items-center rounded-[10px] text-sm font-medium p-2.5 h-10 text-white focus:text-white active:text-white no-underline cursor-pointer"
                                href="/subscriptions"
                                style={{ background: 'rgb(236,90,121)' }}
                                whileHover={{
                                    scale: 1.1,
                                    y: -4,
                                    boxShadow: "0 8px 16px rgba(236,90,121, 0.4)"
                                }}
                                whileTap={{ scale: 0.95 }}
                                initial={{ opacity: 0, x: 20 }}
                                animate={{ opacity: 1, x: 0 }}
                                transition={{
                                    type: "spring",
                                    stiffness: 400,
                                    damping: 10
                                }}
                            >
                                <div className="flex justify-center items-center">
                                    <div>
                                        {t('settings.upgradeToPremium')}
                                    </div>
                                </div>
                            </motion.a>
                        </div>

                        {/* 取消订阅的按钮  */}
                        <div className="mr-2">
                            <motion.button
                                className="relative flex justify-center w-full items-center rounded-[10px] text-white text-sm font-medium p-2.5 h-10 text-white focus:text-white active:text-white no-underline cursor-pointer"
                                onClick={() => setIsModalOpen(true)}
                                style={{ background: 'rgb(236,90,121)' }}
                                whileHover={{
                                    scale: 1.1,
                                    y: -4,
                                    boxShadow: "0 8px 16px rgba(236,90,121, 0.4)"
                                }}
                                whileTap={{ scale: 0.95 }}
                                initial={{ opacity: 0, x: 20 }}
                                animate={{ opacity: 1, x: 0 }}
                                transition={{
                                    type: "spring",
                                    stiffness: 400,
                                    damping: 10
                                }}
                            >
                                <div className="flex justify-center items-center">
                                    <div>
                                        {t('settings.cancelSubscription')}
                                    </div>
                                </div>
                            </motion.button>
                        </div>

                    </div>
                )}
            </div>

            {/* 确认取消订阅的弹窗 */}
            <ReleasePopUp
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                onConfirm={handleCancelSubscription}
                confirmText={t('settings.confirm')}
                cancelText={t('settings.cancel')}
            />
        </div>
    );
};

export default PlanInfo; 